<!-- 订单管理 -->
<template>
  <PageContainer title="订单管理">
    <!-- 搜索和操作区 -->
    <div class="search-operate">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input v-model="searchForm.orderNo" placeholder="请输入订单编号搜索" prefix-icon="el-icon-search"
            class="search-input"></el-input>
        </el-col>
        <el-col :span="6">
          <el-select v-model="searchForm.status" placeholder="请选择订单状态" class="status-select">
            <el-option label="全部" value=""></el-option>
            <el-option label="待付款" value="pending_payment"></el-option>
            <el-option label="待发货" value="pending_delivery"></el-option>
            <el-option label="已发货" value="delivered"></el-option>
            <el-option label="已完成" value="completed"></el-option>
            <el-option label="已取消" value="cancelled"></el-option>
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-date-picker v-model="searchForm.dateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD" class="date-picker"></el-date-picker>
        </el-col>
        <el-col :span="4" class="operate-buttons">
          <el-button type="success" @click="handleExport">
            <i class="el-icon-download"></i> 导出订单
          </el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 订单统计卡片 -->
    <div class="order-stats" style="margin-top: 20px;">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-header">
              <i class="el-icon-s-order stat-icon"></i>
              <h4>今日订单数</h4>
            </div>
            <div class="stat-value">{{ todayOrderCount }}</div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-header">
              <i class="el-icon-money stat-icon"></i>
              <h4>今日销售额</h4>
            </div>
            <div class="stat-value">¥{{ todaySalesAmount.toFixed(2) }}</div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-header">
              <i class="el-icon-s-shop stat-icon"></i>
              <h4>本月订单数</h4>
            </div>
            <div class="stat-value">{{ monthOrderCount }}</div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-header">
              <i class="el-icon-yen stat-icon"></i>
              <h4>本月销售额</h4>
            </div>
            <div class="stat-value">¥{{ monthSalesAmount.toFixed(2) }}</div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 订单表格 -->
    <el-table :data="orderList" border stripe :loading="loading" style="width: 100%; margin-top: 20px;"
      @row-click="handleRowClick">
      <el-table-column label="订单编号" prop="orderNo" width="180"></el-table-column>
      <el-table-column label="下单用户" prop="username" width="120" align="center"></el-table-column>
      <el-table-column label="用户电话" prop="phone" width="130" align="center"></el-table-column>
      <el-table-column label="订单金额" width="120" align="center">
        <template #default="scope">
          <span style="color: red; font-weight: 600;">¥{{ scope.row.totalAmount.toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" width="120" align="center">
        <template #default="scope">
          <el-tag :type="getStatusTagType(scope.row.status)">
            {{ getStatusLabel(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="支付方式" prop="paymentMethod" width="120" align="center">
        <template #default="scope">
          {{ getPaymentMethodLabel(scope.row.paymentMethod) || '-' }}
        </template>
      </el-table-column>
      <el-table-column label="下单时间" prop="createTime" width="180" align="center"></el-table-column>
      <el-table-column label="操作" width="180" align="center">
        <template #default="scope">
          <el-button type="text" @click="handleViewDetail(scope.row, $event)">详情</el-button>
          <el-button type="text" v-if="scope.row.status === 'pending_delivery'"
            @click="handleShipment(scope.row, $event)" style="color: #1989fa;">
            发货
          </el-button>
          <el-button type="text" v-if="scope.row.status === 'pending_payment'"
            @click="handleCancelOrder(scope.row, $event)" style="color: red;">
            取消
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <TablePagination :total="total" :page-size="pageSize" :current-page="currentPage" @size-change="handleSizeChange"
      @current-change="handleCurrentChange" style="margin-top: 20px; text-align: right;"></TablePagination>

    <!-- 订单详情弹窗 -->
    <el-dialog title="订单详情" :visible.sync="detailVisible" width="800px" :before-close="handleDetailClose">
      <div class="order-detail">
        <div class="detail-header">
          <div class="order-header-left">
            <h3>订单编号：{{ currentOrder.orderNo }}</h3>
            <el-tag :type="getStatusTagType(currentOrder.status)">
              {{ getStatusLabel(currentOrder.status) }}
            </el-tag>
          </div>
          <div class="order-header-right">
            <p>下单时间：{{ currentOrder.createTime }}</p>
            <p>支付时间：{{ currentOrder.payTime || '未支付' }}</p>
          </div>
        </div>

        <div class="detail-section">
          <h4>收货信息</h4>
          <el-table :data="[currentOrder.receiverInfo]" border style="width: 100%;">
            <el-table-column label="收货人" prop="receiverName" width="120" align="center"></el-table-column>
            <el-table-column label="联系电话" prop="receiverPhone" width="150" align="center"></el-table-column>
            <el-table-column label="收货地址" prop="receiverAddress"></el-table-column>
          </el-table>
        </div>

        <div class="detail-section">
          <h4>商品信息</h4>
          <el-table :data="currentOrder.orderItems" border style="width: 100%;">
            <el-table-column label="商品图片" width="100" align="center">
              <template #default="scope">
                <el-image :src="scope.row.productImage" style="width: 60px; height: 60px; object-fit: cover;"
                  fit="cover"></el-image>
              </template>
            </el-table-column>
            <el-table-column label="商品名称" prop="productName" width="200"></el-table-column>
            <el-table-column label="商品单价" prop="productPrice" width="100" align="center">
              <template #default="scope">
                ¥{{ scope.row.productPrice.toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column label="购买数量" prop="quantity" width="100" align="center"></el-table-column>
            <el-table-column label="小计" width="100" align="center">
              <template #default="scope">
                ¥{{ (scope.row.productPrice * scope.row.quantity).toFixed(2) }}
              </template>
            </el-table-column>
          </el-table>
        </div>

        <div class="detail-section">
          <h4>支付信息</h4>
          <el-table :data="[currentOrder.paymentInfo]" border style="width: 100%;">
            <el-table-column label="支付方式" prop="paymentMethod" width="150" align="center">
              <template #default="scope">
                {{ getPaymentMethodLabel(scope.row.paymentMethod) || '-' }}
              </template>
            </el-table-column>
            <el-table-column label="支付金额" prop="paymentAmount" width="150" align="center">
              <template #default="scope">
                ¥{{ scope.row.paymentAmount.toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column label="支付状态" prop="paymentStatus" width="150" align="center">
              <template #default="scope">
                <el-tag :type="scope.row.paymentStatus === 'success' ? 'success' : 'danger'">
                  {{ scope.row.paymentStatus === 'success' ? '支付成功' : '未支付' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="支付时间" prop="paymentTime" width="200" align="center"></el-table-column>
          </el-table>
        </div>

        <div class="detail-section">
          <h4>物流信息</h4>
          <div v-if="currentOrder.logisticsInfo" class="logistics-info">
            <el-table :data="[currentOrder.logisticsInfo]" border style="width: 100%;">
              <el-table-column label="物流公司" prop="logisticsCompany" width="150" align="center"></el-table-column>
              <el-table-column label="物流单号" prop="logisticsNo" width="200" align="center"></el-table-column>
              <el-table-column label="发货时间" prop="shipTime" width="200" align="center"></el-table-column>
              <el-table-column label="确认收货时间" prop="receiveTime" width="200" align="center"></el-table-column>
            </el-table>
          </div>
          <div v-else class="no-logistics">
            <p>暂无物流信息</p>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 发货弹窗 -->
    <el-dialog title="订单发货" :visible.sync="shipmentVisible" width="500px" :before-close="handleShipmentClose">
      <el-form :model="shipmentForm" :rules="shipmentRules" ref="shipmentFormRef" label-width="100px">
        <el-form-item label="物流公司" prop="logisticsCompany">
          <el-input v-model="shipmentForm.logisticsCompany" placeholder="请输入物流公司名称"></el-input>
        </el-form-item>
        <el-form-item label="物流单号" prop="logisticsNo">
          <el-input v-model="shipmentForm.logisticsNo" placeholder="请输入物流单号"></el-input>
        </el-form-item>
        <el-form-item label="发货备注" prop="remark">
          <el-input v-model="shipmentForm.remark" type="textarea" :rows="3" placeholder="请输入发货备注（可选）"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="shipmentVisible = false">取消</el-button>
        <el-button type="primary" @click="handleShipmentSubmit">确认发货</el-button>
      </template>
    </el-dialog>
  </PageContainer>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import PageContainer from '@/components/common/PageContainer.vue'
import TablePagination from '@/components/common/TablePagination.vue'
import { getOrderList, getOrderDetail, cancelOrder, shipOrder, getOrderStats } from '@/api/order'

// 搜索表单
const searchForm = reactive({
  orderNo: '',
  status: '',
  dateRange: []
})

// 表格数据
const orderList = ref([])
const total = ref(0)
const pageSize = ref(10)
const currentPage = ref(1)
const loading = ref(false)

// 统计数据
const todayOrderCount = ref(0)
const todaySalesAmount = ref(0)
const monthOrderCount = ref(0)
const monthSalesAmount = ref(0)

// 弹窗相关
const detailVisible = ref(false)
const shipmentVisible = ref(false)
const currentOrder = ref({})
const shipmentFormRef = ref(null)

// 发货表单
const shipmentForm = reactive({
  orderId: '',
  logisticsCompany: '',
  logisticsNo: '',
  remark: ''
})

// 发货表单校验规则
const shipmentRules = reactive({
  logisticsCompany: [
    { required: true, message: '请输入物流公司名称', trigger: 'blur' }
  ],
  logisticsNo: [
    { required: true, message: '请输入物流单号', trigger: 'blur' }
  ]
})

// 订单状态标签类型
const getStatusTagType = (status) => {
  const statusTypeMap = {
    pending_payment: 'warning',
    pending_delivery: 'info',
    delivered: 'primary',
    completed: 'success',
    cancelled: 'danger'
  }
  return statusTypeMap[status] || 'default'
}

// 订单状态文本
const getStatusLabel = (status) => {
  const statusLabelMap = {
    pending_payment: '待付款',
    pending_delivery: '待发货',
    delivered: '已发货',
    completed: '已完成',
    cancelled: '已取消'
  }
  return statusLabelMap[status] || '未知状态'
}

// 支付方式文本
const getPaymentMethodLabel = (method) => {
  const methodLabelMap = {
    wechat: '微信支付',
    alipay: '支付宝支付',
    unionpay: '银联支付'
  }
  return methodLabelMap[method] || '未知支付方式'
}

// 获取订单列表
const fetchOrderList = async () => {
  try {
    loading.value = true
    const [startDate, endDate] = searchForm.dateRange || []
    const res = await getOrderList({
      orderNo: searchForm.orderNo,
      status: searchForm.status,
      startDate,
      endDate,
      merchantId: localStorage.getItem('merchantId'), // 商家只能查看自己的订单
      pageNum: currentPage.value,
      pageSize: pageSize.value
    })
    orderList.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    ElMessage.error('获取订单列表失败')
  } finally {
    loading.value = false
  }
}

// 获取订单统计
const fetchOrderStats = async () => {
  try {
    const res = await getOrderStats({
      merchantId: localStorage.getItem('merchantId')
    })
    todayOrderCount.value = res.data.todayOrderCount
    todaySalesAmount.value = res.data.todaySalesAmount
    monthOrderCount.value = res.data.monthOrderCount
    monthSalesAmount.value = res.data.monthSalesAmount
  } catch (error) {
    ElMessage.error('获取订单统计失败')
  }
}

// 分页大小改变
const handleSizeChange = (size) => {
  pageSize.value = size
  fetchOrderList()
}

// 页码改变
const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchOrderList()
}

// 查看订单详情
const handleViewDetail = async (row, event) => {
  event.stopPropagation() // 阻止行点击事件
  try {
    const res = await getOrderDetail(row.id)
    currentOrder.value = res.data
    detailVisible.value = true
  } catch (error) {
    ElMessage.error('获取订单详情失败')
  }
}

// 取消订单
const handleCancelOrder = async (row, event) => {
  event.stopPropagation()
  try {
    await ElMessageBox.confirm(
      '确定要取消该订单吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    await cancelOrder(row.id)
    ElMessage.success('订单取消成功')
    fetchOrderList()
  } catch (error) {
    ElMessage.error('订单取消失败')
  }
}

// 发货
const handleShipment = (row, event) => {
  event.stopPropagation()
  shipmentForm.orderId = row.id
  shipmentForm.logisticsCompany = ''
  shipmentForm.logisticsNo = ''
  shipmentForm.remark = ''
  shipmentVisible.value = true
}

// 确认发货
const handleShipmentSubmit = async () => {
  try {
    await shipmentFormRef.value.validate()
    await shipOrder(shipmentForm)
    ElMessage.success('发货成功')
    shipmentVisible.value = false
    fetchOrderList()
  } catch (error) {
    ElMessage.error('发货失败')
  }
}

// 行点击事件（展开详情）
const handleRowClick = async (row) => {
  try {
    const res = await getOrderDetail(row.id)
    currentOrder.value = res.data
    detailVisible.value = true
  } catch (error) {
    ElMessage.error('获取订单详情失败')
  }
}

// 导出订单
const handleExport = () => {
  // 实际项目中实现导出逻辑
  ElMessage.success('订单导出成功')
}

// 关闭详情弹窗
const handleDetailClose = () => {
  detailVisible.value = false
  currentOrder.value = {}
}

// 关闭发货弹窗
const handleShipmentClose = () => {
  shipmentFormRef.value?.resetFields()
  shipmentVisible.value = false
}

// 页面挂载时获取数据
onMounted(() => {
  fetchOrderList()
  fetchOrderStats()
})
</script>

<style scoped lang="scss">
.search-operate {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 10px;

  .search-input {
    width: 100%;
  }

  .status-select {
    width: 100%;
  }

  .date-picker {
    width: 100%;
  }

  .operate-buttons {
    display: flex;
    justify-content: flex-end;
  }
}

.order-stats {
  .stat-card {
    height: 120px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    padding: 15px;

    .stat-header {
      display: flex;
      align-items: center;
      gap: 10px;

      .stat-icon {
        font-size: 20px;
        color: #1989fa;
      }

      h4 {
        font-size: 14px;
        color: #666;
        font-weight: normal;
      }
    }

    .stat-value {
      font-size: 24px;
      font-weight: 600;
      color: #333;
    }
  }
}

.order-detail {
  .detail-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 10px;
    border-bottom: 1px solid #e6e6e6;

    .order-header-left {
      display: flex;
      align-items: center;
      gap: 10px;

      h3 {
        font-size: 16px;
        font-weight: 600;
      }
    }

    .order-header-right {
      text-align: right;

      p {
        font-size: 14px;
        color: #666;
        margin-bottom: 5px;
      }
    }
  }

  .detail-section {
    margin-bottom: 20px;

    h4 {
      font-size: 14px;
      font-weight: 600;
      margin-bottom: 10px;
      color: #333;
    }
  }

  .logistics-info {
    margin-top: 10px;
  }

  .no-logistics {
    text-align: center;
    padding: 20px;
    color: #999;
  }
}
</style>